#include <stdio.h>
#include <stdlib.h>
#include "hash.h"

void InitHashTable(HashTable ht)
{
        for (int i = 0; i < P; i++)
                ht[i] = NULL;
}

static int Hash(datatype *key)
{
        return *key % P;
}

void InsertHashTable(HashTable ht, datatype *key)
{
        int index = Hash(key);
        HashNode *new = malloc(sizeof(HashNode));
        new->data = *key;
        new->link = ht[index];
        ht[index] = new;
}

void ShowHashTable(HashTable ht)
{
        for (int i = 0; i < P; i++)
        {
                printf("%d : ", i);
                HashNode *ptr = ht[i];
                while (ptr != NULL)
                {
                        printf("%d-->", ptr->data);
                        ptr = ptr->link;
                }
                printf("Nul.\n");
        }
}

HashNode *SearchHashTable(HashTable ht, datatype *key)
{
        int index = Hash(key);
        if (index < 0 || index > P)
                return NULL;
        HashNode *ptr = ht[index];
        while (ptr != NULL)
        {
                if (ptr->data == *key)
                        return ptr;
                ptr = ptr->link;
        }
        return NULL;
}

int RemoveHashTable(HashTable ht, datatype *key)
{
        HashNode *ptr = SearchHashTable(ht, key);
        if (ptr == NULL)
                return -1;
        int index = Hash(key);
        HashNode *current = ht[index];
        if (current == ptr)
        {
                ht[index] = NULL;
                free(ptr);
                return 0;
        }
        while (current->link != ptr)
                current = current->link;
        current->link = ptr->link;
        free(ptr);

        return 0;
}